package com.gaming.glb;

import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.texture.region.TextureRegion;

public class Arrow extends BaseEntity {
	
	
	private final float MAGNITUD_FORZE = 135.34F;
	
	private int mRotation;
	
	public Arrow(int pX, int pY, TextureRegion pTextureRegion, PhysicBall ball, int rotation) {
		newEntity = new Sprite(pX, pY, pTextureRegion){
			@Override
		    public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
				if (!Arrow.this.mBall.isMoving()) {
					this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2);
				}				
	            
				return true;
		    }
		};
	    super.baseTextureRegion = pTextureRegion;
	    this.mBall = ball;
	    this.mRotation = rotation;
	    
	    super.width = super.baseTextureRegion.getWidth();
	    super.height = super.baseTextureRegion.getHeight();
	}

	@Override
	public void attachToScene(Scene scene) 
	{	
		newEntity.setScale(2);
       
		newEntity.setRotation(mRotation);
        scene.attachChild(newEntity); 
        scene.registerTouchArea(newEntity); 
        
        scene.registerUpdateHandler(new IUpdateHandler(){
			@Override
			public void reset() { }

			@Override
			public void onUpdate(final float pSecondsElapsed) { 	
				
				if(mBall != null && mBall.getSprite() != null && Arrow.this.getSprite() != null && mBall.getSprite().collidesWith((Sprite)Arrow.this.getSprite())){
     	        	
     	        	final float force = pSecondsElapsed * MAGNITUD_FORZE;
     	        	final float forceX = (float)(force * Math.cos(Arrow.this.getRotation()*(Math.PI/180F)));
     	        	final float forceY = (float)(force * Math.sin(Arrow.this.getRotation()*(Math.PI/180F)));    	        			
     	        	
     	        	mBall.getBody().setLinearVelocity(mBall.getBody().getLinearVelocity().add(forceX, forceY));
     	        }
			}
		}); 	
	}	
	
	public float getRotation() {
		return mRotation;
	}

}
